package com.augrain.microframework.trace.util;


import com.augrain.microframework.core.util.IpUtils;
import com.augrain.microframework.core.util.StringUtils;
import com.augrain.microframework.trace.TraceConstant;
import com.augrain.microframework.trace.common.TraceLabel;
import com.augrain.microframework.trace.common.spanid.SpanIdGenerator;
import com.augrain.microframework.trace.common.traceid.TraceIdLoader;
import jakarta.servlet.http.HttpServletRequest;

/**
 * trace工具类
 *
 * @author biaoy
 * @since 2021/08/21
 */
public class TraceUtils {

    private TraceUtils() {

    }

    public static TraceLabel build(HttpServletRequest request) {
        String traceId = request.getHeader(TraceConstant.TRACE_ID);
        if (StringUtils.isNotBlank(traceId)) {
            String spanId = request.getHeader(TraceConstant.SPAN_ID);
            String fromApp = request.getHeader(TraceConstant.FROM_APP);
            String fromIp = request.getHeader(TraceConstant.FROM_IP);
            return new TraceLabel(fromApp, fromIp, traceId, spanId);
        }
        return init(request);
    }

    public static TraceLabel init(HttpServletRequest request) {
        TraceLabel label = new TraceLabel();
        label.setTraceId(TraceIdLoader.getIdGenerator().generateTraceId());
        label.setSpanId(SpanIdGenerator.INITIAL_VALUE);
        label.setFromApp(TraceConstant.UNKNOWN);
        if (request != null) {
            label.setFromIp(IpUtils.getRemoteIp(request));
        } else {
            label.setFromIp(TraceConstant.UNKNOWN);
        }
        return label;
    }
}
